import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AskForm } from '../entities/askform.entity';

@Injectable()
export class AskFormService {
    constructor(
        @InjectRepository(AskForm)
        private askFormRepository: Repository<AskForm>,
    ) {}

    async findAll(): Promise<AskForm[]> {
        return this.askFormRepository.find({
            relations: ['replies'],
            order: {
                id: 'DESC'
            }
        });
    }

    async findOne(id: number): Promise<AskForm> {
        const askForm = await this.askFormRepository.findOne({
            where: { id },
            relations: ['replies']
        });
        if (!askForm) {
            throw new NotFoundException(`AskForm with ID ${id} not found`);
        }
        return askForm;
    }

    async create(askForm: AskForm): Promise<AskForm> {
        return this.askFormRepository.save(askForm);
    }

    async update(id: number, askForm: AskForm): Promise<AskForm> {
        await this.findOne(id); // Check if it exists
        await this.askFormRepository.update(id, askForm);
        return this.findOne(id); // Return updated form
    }

    async remove(id: number): Promise<void> {
        const result = await this.askFormRepository.delete(id);
        if (result.affected === 0) {
            throw new NotFoundException(`AskForm with ID ${id} not found`);
        }
    }

    async findUnansweredForms(): Promise<AskForm[]> {
        const forms = await this.askFormRepository.find({
            where: { isAnswered: false },
            relations: ['replies'],
            order: {
                id: 'DESC'
            }
        });

        // 清除已删除的回复
        forms.forEach(form => {
            form.replies = [];
        });

        return forms;
    }

    async findByUserId(userId: string): Promise<AskForm[]> {
        return this.askFormRepository.find({
            where: { submitterUserId: userId },
            relations: ['replies'],
            order: {
                id: 'DESC'
            }
        });
    }
} 